package erp.education.server.db.implementation.common;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import erp.education.server.db.interfaces.common.BaseDAOI;

public class BaseDAO implements BaseDAOI {
	@Autowired
	SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public Session getEntityManager() {
		if (getSessionFactory().getCurrentSession().isOpen()) {
			getSessionFactory().getCurrentSession().close();
		}
		return getSessionFactory().getCurrentSession();
	}

	public Session getCurrentSession() {
		return getSessionFactory().getCurrentSession();

	}

	public Object getSingleResult(String sql, Map params) {
		Object result = null;
		Session session = getEntityManager();
		session.beginTransaction();
		Query query = session.createQuery(sql);
		Iterator map = params.keySet().iterator();
		while (map.hasNext()) {
			String param = map.next().toString();
			query.setParameter(param, params.get(param));
		}
		try {
			result = query.uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();

		}
		return result;
	}

	public List<?> getResultList(String sql, Map params) {
		List<?> result = null;
		Session session = getEntityManager();
		session.beginTransaction();
		Query query = session.createQuery(sql);
		Iterator map = params.keySet().iterator();
		while (map.hasNext()) {
			String param = map.next().toString();
			query.setParameter(param, params.get(param));
		}
		try {
			result = query.list();
		} catch (Exception e) {
			e.getClass();
			e.printStackTrace();
		}
		return result;
	}

	public Object merge(Object entity) {

		Session session = getEntityManager();
		session.beginTransaction();
		try {
			session.merge(entity);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();

		}
		// session.flush();
		return entity;

	}
}
